package com.zHan.system.controller.system;

import com.zHan.common.result.Result;
import com.zHan.common.utils.JwtUtil;
import com.zHan.common.utils.MD5Util;
import com.zHan.common.utils.ThreadLocalUtil;
import com.zHan.model.dto.LoginDto;
import com.zHan.model.system.SysUser;
import com.zHan.system.exception.MyException;
import com.zHan.system.service.ISysLoginLogService;
import com.zHan.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: IndexController
 * Description:
 * date: 2023/6/21 0021 14:38
 * 后台登录管理
 *
 * @author zHan
 */

@Api(tags = "后台登录管理接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysLoginLogService loginLogService;

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录功能")
    public Result login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        String username = loginDto.getUsername();
        // 根据username查询数据
        SysUser sysUser = userService.getUserInfoByUserName(username);
        //如果数据为空
        if (sysUser == null) {
            throw new MyException(20001, "用户不存在");
        }
        // 判断密码是否一致
        String password = loginDto.getPassword();
        String encrypt = MD5Util.encrypt(password);
        if (!encrypt.equals(sysUser.getPassword())) {
            throw new MyException(20001, "密码错误");
        }
        // 判断用户是否可用
        if (sysUser.getStatus() == 0) {
            throw new MyException(20001, "用户不可用");
        }
        // 根据userId和userName生成token数组，封装成map集合
        String token = JwtUtil.createToken(sysUser.getId(), sysUser.getUsername());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        return Result.ok(map);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取用户信息")
    public Result info() {
        Map<String, String> map = ThreadLocalUtil.get();
        String username = map.get("username");
        // 根据用户名获取用户信息（基本信息、菜单权限和按钮权限信息）
        Map<String, Object> userInfoMap = userService.getUserByUserName(username);

        return Result.ok(userInfoMap);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录")
    public Result logout() {
        return Result.ok();
    }

}
